<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getSoftTypesApi,
  AddClientVersionApi,
  GetVersionsApi,
  delUpgradePackageApi
} from '@/api/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElUpload, ElIcon, FormRules, ElMessageBox } from 'element-plus'
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { Plus } from '@element-plus/icons-vue'
const PATH_URL = import.meta.env.VITE_API_BASE_PATH
import { useUserStoreWithOut } from '@/store/modules/user'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import { Form, FormSchema } from '@/components/Form'
import type { UploadInstance } from 'element-plus'
import UpgradeDetail from './UpgradeDetail.vue'
import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const userStore = useUserStoreWithOut()
const uploadUrl = PATH_URL + 'api/Version/AddClientVersion'
const headers = ref({ Authorization: userStore.getToken ?? '' })
const { t } = useI18n()

const { required } = useValidator()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await GetVersionsApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount
    }
  }
})

const { dataList, loading, total, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'clientType',
    label: '客户端类型'
  },
  {
    field: 'versionNo',
    label: '版本号'
  },
  {
    field: 'versionPath',
    label: '版本路径'
  },

  {
    field: 'createTime',
    label: t('tableDemo.displayTime')
  },
  {
    field: 'remark',
    label: t('userDemo.remark')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="success" onClick={() => look(row)}>
              升级记录
            </BaseButton>
            <BaseButton type="danger" onClick={() => del(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'clientType',
    label: '客户端类型',
    component: 'Select',
    componentProps: {
      placeholder: '请选择'
    },
    optionApi: async () => {
      return typeList.value
    }
  },
  {
    field: 'versionNo',
    label: '版本号',
    component: 'Input'
  },
  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
const dialogVisible = ref(false)
const saveLoading = ref(false)
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    dialogVisible.value = false
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const errorFile = (e) => {
  ElMessage.error(e.msg || '导入失败')
  console.log('errorFile-------', e)
}
const versionGuid = ref('')
const showDialog = ref(false)
const look = (row) => {
  versionGuid.value = row.guid
  showDialog.value = true
}

interface labelSelect {
  label: string
  value: string
}
const typeList = ref<labelSelect[]>([])
const getSoftTypes = async () => {
  const r = await getSoftTypesApi()
  let devList: labelSelect[] = []
  r.data?.map((item) => {
    devList.push({
      label: item.configName,
      value: item.configName
    })
  })
  typeList.value = devList
}
getSoftTypes()

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
const uploadRef = ref<UploadInstance>()
const addformDt = ref()
let UpFile = null
const beforeUpload = (file) => {
  const MAX_SIZE = 1024 * 1024 * 1024 //1G
  console.log('file-------', file)
  if (file.name) {
    let fileName = file.name
    let fileArr = fileName.split('.')
    if (fileArr[fileArr.length - 1] != 'zip') {
      ElMessage.error('请上传zip文件')
      return false
    }
  }
  if (file.size > MAX_SIZE) {
    ElMessage.error('文件大小不能超过 1G!')
    return false
  }
  UpFile = file
  // const MAX_SIZE = 1024 * 1024 * 1024 //1G
  // if (file.size > MAX_SIZE) {
  //   ElMessage.error('文件大小不能超过 1G!')
  //   return false
  // }
  return true
}
const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })

  console.log('UpFile----------', uploadRef.value?.fileList)
  // if (!uploadRef.value?.fileList) {
  //   ElMessage.error('请选择文件')
  //   return
  // }

  if (valid) {
    const formData = await getFormData()
    console.log(formData)
    addformDt.value = formData
  }
  uploadRef.value!.submit()
}
const addformSchema = reactive<FormSchema[]>([
  {
    field: 'ClientType',
    label: '客户端类型',
    component: 'Select',
    componentProps: {
      placeholder: '请选择'
    },
    optionApi: async () => {
      return typeList.value
    }
  },
  {
    field: 'VersionNo',
    label: '版本号',
    component: 'Input'
  },

  {
    field: 'remark',
    label: t('userDemo.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  }
  // {
  //   field: 'file',
  //   label: '上传文件',
  //   component: 'Upload',
  //   componentProps: {
  //     placeholder: '请选择文件',
  //     readonly: true,
  //     autoUpload: false,
  //     action: uploadUrl,
  //     limit: 1,
  //     drag: true,
  //     accept: '.zip, .xls',
  //     headers: headers,
  //     data: addformDt.value,
  //     onSuccess: (e) => {
  //       console.log('successFile-------', e)
  //       if (e.code == 0) {
  //         ElMessage.success('添加成功')
  //         dialogVisible.value = false
  //         getList()
  //       } else {
  //         ElMessage.error(e.msg || '导入失败')
  //       }
  //     },
  //     slots: {
  //       default: () => (
  //         <>
  //           <ElIcon class="el-icon--upload">
  //             <Plus />
  //           </ElIcon>
  //         </>
  //       )
  //     }
  //   }
  // }
])

const rules = reactive({
  ClientType: [required()],
  VersionNo: [required()]
})

const del = (row) => {
  ElMessageBox.confirm('是否删除该文件', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const r = await delUpgradePackageApi({
      versionGuid: row.guid
    })
    getList()
    ElMessage.success(r.msg || '删除成功')
  })
}
const addFile = () => {
  UpFile = null
  dialogVisible.value = true
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px" v-if="haspermiss.includes('新增')">
      <BaseButton type="primary" @click="addFile">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
    <Dialog v-model="dialogVisible" title="新增">
      <Form :rules="rules" :schema="addformSchema" @register="formRegister" />
      <!--  :action="uploadUrl" -->
      <ElUpload
        accept=".zip,.rar,.7z"
        drag
        action="/api/Version/AddClientVersion"
        :headers="headers"
        :data="addformDt"
        :limit="1"
        name="VersionFile"
        ref="uploadRef"
        :auto-upload="false"
        :show-file-list="true"
        :on-success="successFile"
        :on-error="errorFile"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.zip最大支持1G</div>
      </ElUpload>
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="showDialog" title="升级记录">
      <UpgradeDetail :versionGuid="versionGuid" />
      <template #footer>
        <BaseButton @click="showDialog = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
